package com.example.contextcube;

import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageButton;
import android.widget.TextView;

import com.example.contextcube.base.BaseActivity;
import com.example.contextcube.db.DictionaryDatabaseHelper;
import com.example.contextcube.model.Word;
import com.example.contextcube.util.FavoriteManager;
import com.example.contextcube.util.ToastManager;
import com.google.android.material.appbar.CollapsingToolbarLayout;

public class WordDetailActivity extends BaseActivity {
    private static final String TAG = "WordDetailActivity";

    private TextView wordText;
    private TextView phoneticText;
    private TextView definitionText;
    private TextView translationText;
    private ImageButton favoriteButton;
    private DictionaryDatabaseHelper dbHelper;
    private CollapsingToolbarLayout collapsingToolbar;
    private FavoriteManager favoriteManager;
    private String currentWord;
    private boolean isFavorited = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_word_detail);

        Log.d(TAG, "onCreate: 初始化单词详情页");
        
        // 初始化数据库
        dbHelper = new DictionaryDatabaseHelper(this);
        
        // 初始化收藏管理器
        favoriteManager = FavoriteManager.getInstance();
        favoriteManager.setDatabaseHelper(dbHelper);

        // 初始化视图
        initViews();
        
        // 设置工具栏
        setupToolbar();
        
        // 获取传递的单词数据
        Intent intent = getIntent();
        if (intent != null) {
            String wordText = intent.getStringExtra("word");
            Log.d(TAG, "onCreate: 获取到单词: " + wordText);
            
            if (!TextUtils.isEmpty(wordText)) {
                // 保存当前单词
                currentWord = wordText;
                
                // 获取完整单词信息
                if (intent.hasExtra("phonetic") && intent.hasExtra("definition") && intent.hasExtra("translation")) {
                    // 如果Intent中包含完整信息，直接使用
                    String phonetic = intent.getStringExtra("phonetic");
                    String definition = intent.getStringExtra("definition");
                    String translation = intent.getStringExtra("translation");
                    
                    Log.d(TAG, "onCreate: 使用Intent中的完整信息");
                    displayWordDetails(wordText, phonetic, definition, translation);
                    
                    // 添加到最近查询
                    addToRecentQueries(wordText, phonetic, definition, translation);
                } else {
                    // 否则从数据库加载
                    Log.d(TAG, "onCreate: 从数据库加载单词详情");
                    loadWordDetails(wordText);
                }
                
                // 更新收藏状态
                updateFavoriteStatus();
            } else {
                Log.d(TAG, "onCreate: 没有传递单词，显示Hello示例");
                currentWord = "Hello";
                displayWordDetails("Hello", "/həˈləʊ/", "An expression used to greet someone", "用作问候语,表示'你好'");
                updateFavoriteStatus();
            }
        }
    }
    
    private void initViews() {
        Log.d(TAG, "initViews: 初始化视图组件");
        
        wordText = findViewById(R.id.word_text);
        phoneticText = findViewById(R.id.phonetic_text);
        definitionText = findViewById(R.id.definition_text);
        translationText = findViewById(R.id.translation_text);
        favoriteButton = findViewById(R.id.favorite_button);
        collapsingToolbar = findViewById(R.id.collapsing_toolbar);
        
        // 设置按钮点击事件
        favoriteButton.setOnClickListener(v -> {
            // 收藏功能
            Log.d(TAG, "onClick: 点击收藏按钮");
            toggleFavorite();
        });
    }
    
    /**
     * 更新收藏状态并设置UI
     */
    private void updateFavoriteStatus() {
        if (currentWord != null) {
            // 获取当前收藏状态
            isFavorited = favoriteManager.isFavorited(currentWord);
            updateFavoriteButton();
        }
    }
    
    /**
     * 根据收藏状态更新按钮UI
     */
    private void updateFavoriteButton() {
        if (isFavorited) {
            favoriteButton.setImageResource(R.drawable.ic_favorite);
        } else {
            favoriteButton.setImageResource(R.drawable.ic_favorite_border);
        }
    }
    
    /**
     * 切换收藏状态
     */
    private void toggleFavorite() {
        if (currentWord == null) return;
        
        // 切换收藏状态
        isFavorited = !isFavorited;
        updateFavoriteButton();
        
        // 更新数据库
        boolean success = favoriteManager.toggleFavorite(currentWord, isFavorited);
        
        if (success) {
            // 提示用户
            String message = isFavorited ? 
                    getString(R.string.added_to_favorites, currentWord) : 
                    getString(R.string.removed_from_favorites, currentWord);
            ToastManager.showShort(this, message);
        } else {
            // 操作失败，恢复状态并显示错误
            isFavorited = !isFavorited;
            updateFavoriteButton();
            
            String message = isFavorited ? 
                    getString(R.string.favorite_add_failed, currentWord) : 
                    getString(R.string.favorite_remove_failed, currentWord);
            ToastManager.showShort(this, message);
        }
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        
        // 显示返回按钮
        if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        
            // 不显示标题栏标题
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
        
        // 确保CollapsingToolbarLayout不显示标题
        collapsingToolbar.setTitle("");
        collapsingToolbar.setExpandedTitleColor(getResources().getColor(android.R.color.transparent));
        collapsingToolbar.setCollapsedTitleTextColor(getResources().getColor(android.R.color.transparent));
    }
    
    private void loadWordDetails(final String wordText) {
        Log.d(TAG, "loadWordDetails: 开始从数据库加载单词: " + wordText);
        
        // 在后台线程加载单词详情
        new Thread(() -> {
            try {
                final Word word = dbHelper.getWord(wordText);
                
                // 在UI线程更新界面
                runOnUiThread(() -> {
                    if (word != null) {
                        Log.d(TAG, "loadWordDetails: 加载成功: " + word.getWord());
                        displayWordDetails(word.getWord(), word.getPhonetic(), 
                                          word.getDefinition(), word.getTranslation());
                        
                        // 添加到最近查询
                        addToRecentQueries(word);
                    } else {
                        Log.d(TAG, "loadWordDetails: 未找到单词: " + wordText);
                        displayWordDetails(wordText, "", "No definition found", "未找到释义");
                    }
                });
            } catch (Exception e) {
                Log.e(TAG, "loadWordDetails: 加载出错: " + e.getMessage(), e);
                
                runOnUiThread(() -> {
                    displayWordDetails(wordText, "", "Error loading definition", "加载释义出错");
                });
            }
        }).start();
    }
    
    private void displayWordDetails(String word, String phonetic, String definition, String translation) {
        Log.d(TAG, "displayWordDetails: 显示单词: " + word);
        
        // 显示单词信息
        wordText.setText(word);
        
        // 显示音标，如果有
        if (!TextUtils.isEmpty(phonetic)) {
            phoneticText.setText(phonetic);
            phoneticText.setVisibility(TextView.VISIBLE);
        } else {
            phoneticText.setVisibility(TextView.GONE);
        }
        
        // 显示英文释义
        definitionText.setText(definition);
        
        // 显示中文翻译
        translationText.setText(translation);
    }
    
    /**
     * 添加单词到最近查询
     */
    private void addToRecentQueries(String word, String phonetic, String definition, String translation) {
        Log.d(TAG, "addToRecentQueries: 添加单词到最近查询: " + word);
        
        Word wordObj = new Word();
        wordObj.setWord(word);
        wordObj.setPhonetic(phonetic);
        wordObj.setDefinition(definition);
        wordObj.setTranslation(translation);
        
        dbHelper.addToRecentQueries(wordObj);
    }
    
    /**
     * 添加单词对象到最近查询
     */
    private void addToRecentQueries(Word word) {
        Log.d(TAG, "addToRecentQueries: 添加单词对象到最近查询: " + word.getWord());
        dbHelper.addToRecentQueries(word);
    }
    
    @Override
    public boolean onSupportNavigateUp() {
        Log.d(TAG, "onSupportNavigateUp: 返回上一页");
        onBackPressed();
        return true;
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: 单词详情页被销毁");
    }
} 